package com.ali.demo.unicom.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.ali.demo.unicom.domain.Demo;
import com.ali.demo.unicom.service.DemoService;
import com.alibaba.fastjson.JSONObject;

@Controller
public class DemoController {
    private static final Logger log = LoggerFactory
	    .getLogger(DemoController.class);

    @Autowired
    private DemoService demoService;

    @RequestMapping(value = { "/demo.json" }, method = { RequestMethod.GET, RequestMethod.POST })
    public void queryDemo(HttpServletRequest request,
	    HttpServletResponse response, @RequestParam("ID") long demoID)
	    throws IOException {
	PrintWriter writer = response.getWriter();
	Demo demo = demoService.getDemoByID(demoID);
	if (demo == null) {
	    log.error("ID " + demoID + " not found");
	    response.sendError(404, "ID " + demoID + " not found");
	    return;
	}
	writer.write(JSONObject.toJSONString(demo));
    }

    @RequestMapping(value = { "/demo.html" }, method = RequestMethod.GET)
    public ModelAndView viewDemo(@RequestParam("ID") long demoID, ModelMap map)
	    throws IOException {
	Demo demo = demoService.getDemoByID(demoID);
	if (demo == null) {
	    log.error("ID " + demoID + " not found");
	    map.put("errmsg", "ID " + demoID + " not found");
	} else {
	    map.put("demo", demo);
	}
	return new ModelAndView("demo");
    }
}
